<script lang="ts" setup>
import { ref, computed, onMounted, Ref } from "vue";
import { Delete } from "@element-plus/icons-vue";
import {
  addMediatorOrganization,
  deleteMediatorOrganization,
  getAllOrganizations,
  updateOrganization,
} from "@/axios/mediator/mediatorReq";
import { ElMessage } from "element-plus";
import { create } from "domain";
import MediatorsOrganization from "@/types/response/mediatorsOrganization";
import Mediator from "@/types/response/mediator";

const mediatorsOrgs: Ref<MediatorsOrganization[]> = ref([]);

// 控制添加调解组织弹窗
const dialogVisible = ref(false);

// 添加调解组织数据模型
const mediatorsOrgModel: Ref<MediatorsOrganization> = ref({
  organizationId: null,
  branchName: "",
  affiliationName: "",
  jurisdiction: "",
  chargeMan: "",
  chargePhone: "",
  createdTime: "",
});

// 状态选择框绑定的值
const stateValue = ref("");

const rulesFormRef = ref();

// 添加调解组织表单校验
const rules = {
  branchName: [
    { required: true, message: "请输入分支机构名称", trigger: "blur" },
  ],
  affiliationName: [
    { required: true, message: "请输入所属机构名称", trigger: "blur" },
  ],
  jurisdiction: [{ required: true, message: "请输入管辖地", trigger: "blur" }],
  chargeMan: [{ required: true, message: "请输入负责人", trigger: "blur" }],
  chargePhone: [
    { required: true, message: "请输入负责人电话", trigger: "blur" },
  ],
};
//添加调解组织函数
const addMediatorsOrg = () => {
  title.value = "新增调解组织";
  dialogVisible.value = true;
  stateValue.value = "";
  editIndex.value = null;
  rulesFormRef.value?.resetFields();
};

const editIndex = ref<number | null>(null);

const editMediatorsOrg = (
  index: number,
  mediatorsOrg: MediatorsOrganization
) => {
  title.value = "编辑调解组织";
  dialogVisible.value = true;
  mediatorsOrgModel.value = { ...mediatorsOrg };
  editIndex.value = index;
};

const validateForm = () => {
  rulesFormRef.value.validate((valid) => {
    if (valid) {
      submitForm();
    }
  });
};

// 提交表单的方法
const submitForm = async () => {
  if (editIndex.value !== null) {
    // 更新调解组织信息
    try {
      const success = await updateOrganization(mediatorsOrgModel.value);
      if (success) {
        mediatorsOrgs.value[editIndex.value] = { ...mediatorsOrgModel.value };
        editIndex.value = null;
        ElMessage.success("调解组织更新成功");
      } else {
        ElMessage.error("调解组织更新失败");
      }
    } catch (error) {
      console.error("修改信息失败:", error);
      ElMessage.error("系统错误，请稍后再试");
    }
  } else {
    // 添加调解组织信息
    try {
      const newOrg = await addMediatorOrganization(mediatorsOrgModel.value);
      if (newOrg) {
        mediatorsOrgs.value.push(newOrg);
        stateValue.value = "";
        ElMessage.success("调解组织添加成功");
      } else {
        ElMessage.error("调解组织添加失败");
      }
    } catch (error) {
      console.error("添加调解组织失败", error);
      ElMessage.error("系统错误，请稍后再试");
    }
  }
  dialogVisible.value = false;
};
// 删除调解组织的方法
const deleteMediatorsOrg = async (index: number) => {
  const mediatorsOrg = mediatorsOrgs.value[index];
  if (editIndex.value === index) {
    editIndex.value = null;
  }
  try {
    const success = await deleteMediatorOrganization(
      mediatorsOrg.organizationId
    );
    if (success) {
      mediatorsOrgs.value.splice(index, 1);
      ElMessage.success("调解组织删除成功");
    } else {
      ElMessage.error("调解组织删除失败");
    }
  } catch (error) {
    console.error("Error deleting mediator organization:", error);
    ElMessage.error("系统错误，请稍后再试");
  }
};

const title = ref("");
const value1 = ref("");

const table = ref(false);
const selectedMediatorsOrg: Ref<MediatorsOrganization> = ref(null);

const openDrawer = (respondent: any) => {
  selectedMediatorsOrg.value = respondent;
  table.value = true;
};

// 获取所有调解组织
onMounted(async () => {
  try {
    mediatorsOrgs.value = await getAllOrganizations();
  } catch (error) {
    console.error("Error fetching mediator organizations:", error);
  }
});
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>调解组织管理</span>
        <div class="extra">
          <el-button type="primary" @click="addMediatorsOrg"
            >新增调解组织</el-button
          >
        </div>
      </div>
    </template>
    <el-table style="width: 100%" :data="mediatorsOrgs">
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column label="分支机构名称" prop="branchName"></el-table-column>
      <el-table-column
        label="所属机构名称"
        prop="affiliationName"
      ></el-table-column>
      <el-table-column label=" 管辖地" prop="jurisdiction"></el-table-column>
      <el-table-column label="负责人" prop="chargeMan"></el-table-column>
      <el-table-column label="负责人电话" prop="chargePhone"></el-table-column>
      <el-table-column label="操作" width="250px">
        <template #default="scope">
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="deleteMediatorsOrg(scope.$index)"
          ></el-button>
          <el-button text type="primary" @click="openDrawer(scope.row)"
            >详细</el-button
          >
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form
        :model="mediatorsOrgModel"
        :rules="rules"
        label-width="140px"
        style="padding-right: 30px"
        ref="rulesFormRef"
      >
        <el-form-item label="分支机构名称" prop="branchName">
          <el-input
            v-model="mediatorsOrgModel.branchName"
            minlength="2"
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属机构名称" prop="affiliationName">
          <el-input
            v-model="mediatorsOrgModel.affiliationName"
            minlength="2"
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item label="管辖地" prop="jurisdiction">
          <el-input
            v-model="mediatorsOrgModel.jurisdiction"
            minlength="2"
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="chargeMan">
          <el-input
            v-model="mediatorsOrgModel.chargeMan"
            minlength="2"
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人电话" prop="chargePhone">
          <el-input
            v-model="mediatorsOrgModel.chargePhone"
            minlength="11"
            maxlength="11"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>

  <el-drawer
    v-model="table"
    title="调解组织详细信息"
    direction="rtl"
    size="50%"
  >
    <el-descriptions :column="1" border :data="selectedMediatorsOrg">
      <el-descriptions-item label="分支机构名称">{{
        selectedMediatorsOrg?.branchName
      }}</el-descriptions-item>
      <el-descriptions-item label="所属机构名称">{{
        selectedMediatorsOrg?.affiliationName
      }}</el-descriptions-item>
      <el-descriptions-item label="管辖地">{{
        selectedMediatorsOrg?.jurisdiction
      }}</el-descriptions-item>
      <el-descriptions-item label="负责人">{{
        selectedMediatorsOrg?.chargeMan
      }}</el-descriptions-item>
      <el-descriptions-item label="负责人联系方式">{{
        selectedMediatorsOrg?.chargePhone
      }}</el-descriptions-item>
    </el-descriptions>
  </el-drawer>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
